#include"List.h"

ListNode* BuyListNode(LTDataType x)
{
	ListNode* newnode =(ListNode*)malloc(sizeof(ListNode));
	newnode->data = x;
	newnode->next = NULL;
	newnode->prev = NULL;

	return newnode;
}

void ListPrint(ListNode* phead)
{
	ListNode* cur = phead->next;
	while (cur != phead)
	{
		printf("%d->", cur->data);
		cur = cur->next;
	}
	printf("NULL\n");
}

ListNode* Listinit()
{
	ListNode* phead = BuyListNode(0);
	phead->next = phead;
	phead->prev = phead;

	return phead;
}
void Destory(ListNode* phead)
{
	assert(phead);
	ListNode* cur = phead->next;
	while (cur != phead)
	{
		ListNode* next = cur->next;
		free(cur);
		cur = next;
	}
	free(phead);
}
void PushBack(ListNode* phead,LTDataType x)
{
	/*ListNode* newnode = BuyListNode(x);
	ListNode* tail = phead->prev;

	tail->next = newnode;
	newnode->prev = tail;
	newnode->next = phead;
	phead->prev = newnode;*/

	ListInsert(phead, x);

}

void  PopBack(ListNode* phead)
{
	/*assert(phead);
	assert(phead->next != phead);
	ListNode* tail = phead->prev;
	ListNode* newtail = tail->prev;

	newtail->next = phead;
	phead->prev = newtail;
	free(tail);*/


	ListErase(phead->prev);

}

void PushFront(ListNode* phead, LTDataType x)
{
	/*assert(phead);
	ListNode* newnode = BuyListNode(x);
	ListNode* first = phead->next;

	phead->next = newnode;
	newnode->prev = phead;
	newnode->next = first;
	first->prev = newnode;*/

	ListInsert(phead->next, x);
}

void PopFront(ListNode* phead)
{
	/*assert(phead);
	assert(phead->next != phead);
	ListNode* first = phead->next;
	ListNode* second = first->next;

	phead->next = second;
	second->prev = phead;
	free(first);*/
	

	ListErase(phead->next);
}

ListNode* ListFind(ListNode* phead, LTDataType x)
{
	ListNode* cur = phead->next;
	while (cur != phead)
	{
		if (cur->data == x)
		{
			return cur;
		}
	}
	
	return NULL;
}
void ListInsert(ListNode* pos,LTDataType x)
{
	assert(pos);
	ListNode* newnode = BuyListNode(x);
	ListNode* prev = pos->prev;

	prev->next = newnode;
	newnode->prev = prev;
	newnode->next = pos;
	pos->prev = newnode;
}
void ListErase(ListNode* pos)
{
	assert(pos);
	ListNode* prev = pos->prev;
	ListNode* next = pos->next;
	
	prev->next = next;
	next->prev = prev;
	free(pos);
}

bool ListEmpty(ListNode* phead)
{
	if (phead->next == phead)
	{
		return true;
	}
	else
	{
		return false;
	}
}

int ListSize(ListNode* phead)
{
	int count = 0;
	ListNode* cur = phead->next;
	while (cur != phead)
	{
		count++;
		cur = cur->next;
	}

	return count;
}